﻿// Copyright (c)  YISH. All rights reserved.
// Licensed under the MIT License, See License.txt in the project root for license information.

using NSQL.Expressions;
using NSQL.Statements;

namespace NSQL.Builder
{
    public class SqlBuilder : IKeySelect, IKeyFrom, IKeyWhere, IKeyGroupBy, IKeyHaving, IKeyOrderBy, IKeySkip, IKeyLimit
    {
        private readonly SelectStatement _selectStatement = new SelectStatement();

        private SqlBuilder()
        {
        }
        public static IKeySelect Select(params SelectElement[] columns)
        {
            var builder = new SqlBuilder();
            builder._selectStatement.Elements.Add(columns);
            return builder;
        }

        IKeyFrom IHasFrom.From(params ITableOrSubquery[] tables)
        {
            _selectStatement.TableSources.Add(tables);
            return this;
        }
        
        
        IKeyFrom IHasFrom.From(params Table[] tables)
        {
            _selectStatement.TableSources.Add(tables);
            return this;
        }

        IKeyWhere IHasWhere.Where(IPredicateExpression predicate)
        {
            _selectStatement.Predicate = predicate;
            return this;
        }

        IKeyWhere IHasWhere.Where(string condition)
        {
            _selectStatement.Predicate = SqlParser.ParsePredicateExpression(condition);
            return this;
        }

        ISelectStatement IHasBuildSelectStatement.Build() => _selectStatement;

        IKeySkip IHasSkip.Skip(int skip)
        {
            _selectStatement.Skip = skip;
            return this;
        }

        IKeyLimit IHasLimit.Limit(int limit)
        {
            _selectStatement.Limit = limit;
            return this;
        }

        public IKeyGroupBy GroupBy()
        {
            return this;
        }

        public IKeyOrderBy OrderBy()
        {
            return this;
        }

        public IKeyHaving Having(IPredicateExpression having)
        {
            _selectStatement.GroupClause.Having = having;
            return this;
        }
    }
}